package com.cn.longdistancebusstation.scenic.order;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.longdistancebusstation.R;

import com.cn.longdistancebusstation.annotation.ScenicTicketValidType;

import com.cn.longdistancebusstation.base.BaseActivity;
import com.cn.longdistancebusstation.callback.OnRecyclerViewItemClickListener;
import com.cn.longdistancebusstation.callback.OnTouristDeleteListener;
import com.cn.longdistancebusstation.contacter.ContacterDetailActivity;
import com.cn.longdistancebusstation.global.GlobalVariable;
import com.cn.longdistancebusstation.httpHelper.HttpHelper;
import com.cn.longdistancebusstation.httpapi.HttpService;
import com.cn.longdistancebusstation.model.Contacter;
import com.cn.longdistancebusstation.model.DatePrice;
import com.cn.longdistancebusstation.model.Identification;
import com.cn.longdistancebusstation.model.ListResultIII;
import com.cn.longdistancebusstation.model.ListResultV;
import com.cn.longdistancebusstation.model.ScenicOrder;
import com.cn.longdistancebusstation.model.Ticket;
import com.cn.longdistancebusstation.scenic.TouristListActivity;
import com.cn.longdistancebusstation.scenic.calendar.PriceCalendarActivity;
import com.cn.longdistancebusstation.util.ToolUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by mucheng on 2018/3/29.
 */

public class SubmitOrderActivity extends BaseActivity implements View.OnClickListener,OnRecyclerViewItemClickListener,OnTouristDeleteListener {
    private static final int REQUEST_STATION_LIST = 1;
    private static final int REQUEST_CALENDAR = 2;
    private static final int REQUEST_CHOOSE_PASSENGER = 1;
    private static final int RESULT_MEMO=3;

    private TextView mScenicTitleTextView,mAddOrExchangeTextView,mTotalPricesTextView;
    private LinearLayout mOrderInfoTextView;
    private TextView mTicketAmountEditText;
    private TextView mPeriodOfUseTextView;
    private EditText mDateEditText;
    private ImageView mAmountAddImageView,mAmountMinusImageView;
    private RecyclerView mRecyclerView;
    private TouristAdapter mTouristAdapter;
    private Button mSubmitOrderButton;
    private Ticket mTicket;
    private String mScenicName;
    private int mTicketCount =1; //购买数量
    private int mUpTicketAmount;//一次最多可购买票数
    private int mLowTicketAmount;//一次要最少购买的票数
    private OnAmountChangeListener mListener;
    private String mOutingDate;
    private String mScenicId;
    private ArrayList<Contacter> mContacterList=new ArrayList<>();
    private Identification mIdentification;
    private ScenicOrder mScenicOrder;
    private String sdata;
    private Map<String,String> params;
    private String qrcodeIMG;
    private String qrcodeURL;
    private String remotenum;
    private String ordernum;
    private String code;
    private String price;
    private List<DatePrice> mDatePrice=new ArrayList<>();
    private Contacter tempContacter;
    private ArrayList<Contacter> contacterList;
    private String str_cardNo;
    private String str_orderTime;
    private Contacter contacter;
    private BigDecimal mTotalPrice;
    private @ScenicTicketValidType int mTicketValidType;
    private TextView mTouristInfoNoteTextView;
    private String mScenicImgPath;
    private TextView mTouristInfoTextView;
    //零售价(元)
    private BigDecimal mRetailPrice;
    private Double mDouble;
    private LinearLayout mMemoLinearLayout;
    private String memo;
    private TextView mMemoTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_submit_scenic_order);
        getTitleTextView().setText("提交订单");
        initData();
        initView();

    }

    private void initData() {
        memo="";
    }

    private void initView() {
        Intent intent = getIntent();
        mScenicName = intent.getStringExtra("scenicName");
        mScenicId=intent.getStringExtra("scenicId");
        mScenicImgPath =intent.getStringExtra("scenicImage");
        mTicket=(Ticket)intent.getSerializableExtra("ticketInfo");
        mTicketValidType = mTicket.getUUtourist_info();
        //最多可购买票数
        mUpTicketAmount = mTicket.getUUbuy_limit_up()>0 ? mTicket.getUUbuy_limit_up() : 999;
        //最少购买票数
        mLowTicketAmount = mTicket.getUUbuy_limit_low()>1 ? mTicket.getUUbuy_limit_low() : 1;
        mTicketCount = mLowTicketAmount;
        //
        mScenicTitleTextView=(TextView)findViewById(R.id.scenic_title);
        mScenicTitleTextView.setText(mScenicName+"("+mTicket.getUUtitle()+")");
        //
        mOrderInfoTextView=(LinearLayout) findViewById(R.id.infor_of_order_tickets);
        mOrderInfoTextView.setOnClickListener(this);
        //
        mDateEditText=(EditText)findViewById(R.id.editText_select_date);
        mDateEditText.setOnClickListener(this);
        mDateEditText.setInputType(InputType.TYPE_NULL);
        //
        mTicketAmountEditText=(TextView) findViewById(R.id.editText_ticket_amount);
        mTicketAmountEditText.setText(mLowTicketAmount + "");
        //
        mAmountAddImageView=(ImageView) findViewById(R.id.amount_add);
        mAmountAddImageView.setOnClickListener(this);
        mAmountMinusImageView=(ImageView)findViewById(R.id.amount_minus);
        mAmountMinusImageView.setOnClickListener(this);
        mAddOrExchangeTextView=(TextView)findViewById(R.id.textView_add_or_exchange);
        mAddOrExchangeTextView.setOnClickListener(this);
        mTotalPricesTextView=(TextView)findViewById(R.id.amount_price);
        mRetailPrice = new BigDecimal(ToolUtil.fen2Yuan(mTicket.getRetail_price()));
        //默认的总价格

        mTotalPrice = mRetailPrice.multiply(new BigDecimal(mLowTicketAmount));
        mTotalPricesTextView.setText("￥" + mTotalPrice);
        //
        mSubmitOrderButton=(Button)findViewById(R.id.submit_order);
        mSubmitOrderButton.setOnClickListener(this);
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        mOutingDate = dateFormat.format(date);
        mDateEditText.setText(mOutingDate + "(￥"+mRetailPrice+")");
        mPeriodOfUseTextView=(TextView)findViewById(R.id.textView_period);
        mPeriodOfUseTextView.setText(dateFormat.format(date)+"当日使用有效");
        mMemoLinearLayout=(LinearLayout)findViewById(R.id.linearLayout_memo);
        mMemoTextView=(TextView)findViewById(R.id.textView_memo_details);
        mMemoLinearLayout.setOnClickListener(this);
        mTouristInfoNoteTextView=(TextView)findViewById(R.id.textView_info);
        mTouristInfoTextView=(TextView)findViewById(R.id.textView_tourist);
        mRecyclerView=(RecyclerView)findViewById(R.id.tourist_info);
        if(mTicketValidType == 0){
            mTouristInfoNoteTextView.setText("需1位出行游客信息，用于游园身份验证");
        }
        else if(mTicketValidType == 1){
            mTouristInfoNoteTextView.setText("需1位出行游客信息，用于游园身份验证");
        }
        else if(mTicketValidType == 2){
            mTouristInfoNoteTextView.setText("需所有行游客信息，用于游园身份验证");
        }
        mTouristAdapter=new TouristAdapter();
        mRecyclerView.setAdapter(mTouristAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        mTouristAdapter.setmOnRecyclerViewItemClickListener(this);
        mTouristAdapter.setmOnTouristDeleteListener(this);
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.infor_of_order_tickets:
                startActivity(new Intent(SubmitOrderActivity.this, ScheduleNoteActivity.class));
                break;
            case R.id.editText_select_date:
                Intent in=new Intent(SubmitOrderActivity.this, PriceCalendarActivity.class);
                in.putExtra("aid",mTicket.getUUaid());
                in.putExtra("pid",mTicket.getUUpid());
                in.putExtra("date",mOutingDate);
                startActivityForResult(in,REQUEST_CALENDAR);
                break;
            case R.id.amount_minus:
                if(mTicketCount > mLowTicketAmount){
                    mTicketCount--;
                    mTicketAmountEditText.setText(mTicketCount +"");
                    mTotalPrice = mRetailPrice.multiply(new BigDecimal(mTicketCount));
                    mTotalPricesTextView.setText("￥" + mTotalPrice);
                }
                else if(mTicketCount == mLowTicketAmount){
                    Toast.makeText(this,"不能再减啦！",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.amount_add:
                if(mTicketCount < mUpTicketAmount) {
                    mTicketCount++;
                    mTicketAmountEditText.setText(mTicketCount +"");
                    mTotalPrice = mRetailPrice.multiply(new BigDecimal(mTicketCount));
                    mTotalPricesTextView.setText("￥" + mTotalPrice);
                }
                else if(mTicketCount == mLowTicketAmount) {
                    Toast.makeText(this, "票数已达上限", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.linearLayout_memo:
                Intent inte=new Intent(SubmitOrderActivity.this,MemoActivity.class);
                inte.putExtra("memoDetails",mMemoTextView.getText().toString());
                startActivityForResult(inte,RESULT_MEMO);
                break;
            case R.id.textView_add_or_exchange:
                Intent intent=new Intent(SubmitOrderActivity.this, TouristListActivity.class);
                intent.putExtra("data", mContacterList);
                startActivityForResult(intent,REQUEST_CHOOSE_PASSENGER);
                break;
            case R.id.submit_order:
                submitOrder();
                break;
        }
        mTicketAmountEditText.clearFocus();
        if (mListener != null) {
            mListener.onAmountChange(SubmitOrderActivity.this, mTicketCount);
        }
    }

    /*
    * 提交订单
    * */
    private void submitOrder() {
        params = new HashMap<>();
        params.put("searchParam.userId", GlobalVariable.getUserID());
        //
        params.put("searchParam.lid",mScenicId);
        params.put("searchParam.tid",mTicket.getUUid());
        params.put("searchParam.aid",mTicket.getUUaid());
        //
//        params.put("searchParam.lid", "59164");
//        params.put("searchParam.tid", "134722");
//        params.put("searchParam.aid", "81");
        //

        params.put("searchParam.ltitle",mScenicName);
        params.put("searchParam.ttitle",mTicket.getUUtitle());
        params.put("searchParam.tprice", mTicket.getBuy_price());
        params.put("searchParam.price",mTicket.getRetail_price());
        params.put("searchParam.tnum", String.valueOf(mTicketCount));
        params.put("searchParam.playtime", String.valueOf(mOutingDate));
        StringBuilder strNames = new StringBuilder();
        StringBuilder strCardNos = new StringBuilder();
        StringBuilder strPhones = new StringBuilder();
        if(mContacterList.size()!=0) {
            for (int i = 0; i < mContacterList.size(); i++) {
                contacter = mContacterList.get(i);
                String cardNO = contacter.getCardNo();
                SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                editor.putString("cardNO", cardNO);
                editor.commit();
                if (i == 0) {
                    strNames.append(contacter.getName());
                    strCardNos.append(contacter.getCardNo());
                    strPhones.append(contacter.getTelephone());
                } else {
                    strNames.append("," + contacter.getName());
                    strCardNos.append("," + contacter.getCardNo());
                    strPhones.append("," + contacter.getCoupons());
                }
            }
        }
        params.put("searchParam.ordername",strNames.toString());
        params.put("searchParam.ordertel",strPhones.toString());
        params.put("searchParam.personID",strCardNos.toString());
        params.put("searchParam.totalPrice", ToolUtil.yuan2Fen(mTotalPrice+""));
        params.put("searchParam.imagePath", mScenicImgPath);
        params.put("searchParam.memo",memo);
        Log.d("参数",params.toString());

        if(mTicketValidType==0 || mTicketValidType==1){

            if(mContacterList.size()==0){
                Toast.makeText(SubmitOrderActivity.this,"至少添加一位游客",Toast.LENGTH_SHORT).show();
                return;

            }else{
                if(mTicketCount <mContacterList.size()){
                    Toast.makeText(SubmitOrderActivity.this,"票数与游客数量不一致",Toast.LENGTH_SHORT).show();
                    return;
                }else{
                    refer();
                }

            }
        }
        else if(mTicketValidType == 2){
            if(mContacterList.size()>0){
                if(mContacterList.size()> mTicketCount){
                    Toast.makeText(SubmitOrderActivity.this,"票数与游客数量不一致",Toast.LENGTH_SHORT).show();
                    return;
                }else if(mContacterList.size()< mTicketCount){
                    Toast.makeText(SubmitOrderActivity.this,"票数与游客数量不一致",Toast.LENGTH_SHORT).show();
                    return;

                }else{
                    checkPersonID();
                }
            }else{
                Toast.makeText(SubmitOrderActivity.this,"至少添加一位游客",Toast.LENGTH_SHORT).show();
                return;
            }
        }
    }

    private void checkPersonID() {
        Retrofit retrofit=new HttpHelper.HttpServiceBuilder().build().getRetrofit();
        HttpService httpService=retrofit.create(HttpService.class);
        Call<ListResultIII<Identification>> call=httpService.getIdentification(str_cardNo);
        call.enqueue(new Callback<ListResultIII<Identification>>() {
            @Override
            public void onResponse(Call<ListResultIII<Identification>> call, Response<ListResultIII<Identification>> response) {
                ListResultIII result=response.body();
                if(result!=null){
                    if(result.getHead().getSuccess()) {
                        Gson gson = new Gson();
                        Map<String, List<Identification>> scenicMap = result.getBody().getData();
                        List<Identification> list = scenicMap.get("Rec");
                        Type type = new TypeToken<Identification>() {
                        }.getType();
                        String strScenicJSON = new Gson().toJson(list.get(0));
                        mIdentification=gson.fromJson(strScenicJSON, type);
                        sdata=mIdentification.getUUdone();
                        refer();
                    }

                }

            }

            @Override
            public void onFailure(Call<ListResultIII<Identification>> call, Throwable t) {
                hideHud();
                Toast.makeText(SubmitOrderActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void refer() {
        if("".equals(mTicketAmountEditText.getText().toString())){
                Toast.makeText(SubmitOrderActivity.this,"金额为空，不能提交订单",Toast.LENGTH_SHORT).show();
                return;


        }else if("￥0.00".equals(mTotalPricesTextView.getText().toString())){
            Toast.makeText(SubmitOrderActivity.this,"金额为零，不能提交订单",Toast.LENGTH_SHORT).show();
            return;

        }else{
                showHud("正在提交订单，请稍后...");
                Retrofit retrofit = new HttpHelper.HttpServiceBuilder().build().getRetrofit();
                HttpService httpService = retrofit.create(HttpService.class);
                Call<ListResultV<ScenicOrder>> call = httpService.getScenicOrder(params);
                call.enqueue(new Callback<ListResultV<ScenicOrder>>() {
                    @Override
                    public void onResponse(Call<ListResultV<ScenicOrder>> call, Response<ListResultV<ScenicOrder>> response) {
                        hideHud();
                        ListResultV result = response.body();
                        if (result.getHead().getSuccess()) {
                            Gson gson = new Gson();
                            Map<String, String> scenicMap = result.getBody().getData();
                            Type type = new TypeToken<ScenicOrder>() {
                            }.getType();
                            String strScenicOrderJSON = new Gson().toJson(scenicMap);
                            mScenicOrder = gson.fromJson(strScenicOrderJSON, type);
                            Intent in = new Intent(SubmitOrderActivity.this, ScenicOrderDetailsActivity.class);
                            in.putExtra("orderId", mScenicOrder.getOrderId());
                            startActivity(in);
                            finish();
                        } else {
                            String strErr = result.getHead().getMsg();
                            Toast.makeText(SubmitOrderActivity.this, strErr, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<ListResultV<ScenicOrder>> call, Throwable t) {
                        hideHud();
                        Toast.makeText(SubmitOrderActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
        }
    }

    @Override
    public void onClick(int position) {

    }

    @Override
    public void onClickInnerCtrl(int position) {
        Intent in=new Intent(SubmitOrderActivity.this,ContacterDetailActivity.class);
        in.putExtra("contacter",mContacterList.get(position));
        startActivity(in);

    }

    @Override
    public void onClickCoupon(int position) {

    }

    @Override
    public void onClickCheckBox(int position) {

    }

    @Override
    public void onClickDeleteTourist(int position) {
        mContacterList.remove(position);
        mTouristAdapter.notifyDataSetChanged();

    }

    public interface OnAmountChangeListener {
        void onAmountChange(SubmitOrderActivity view, int amount);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data == null) return;
        if(requestCode == REQUEST_CALENDAR){
            mOutingDate = data.getStringExtra("outingDate");
            String strFenPrice = data.getStringExtra("price");
            mRetailPrice = new BigDecimal(strFenPrice);
            mTotalPrice = mRetailPrice.multiply(new BigDecimal(mTicketCount));
            mTotalPricesTextView.setText("￥" + mTotalPrice);


            mDateEditText.setText(mOutingDate + " (￥" + mRetailPrice +")");
            mPeriodOfUseTextView.setText(mOutingDate + "当日使用有效");
        }

        if(requestCode == REQUEST_CHOOSE_PASSENGER){
            if(resultCode == RESULT_OK){
                contacterList = (ArrayList<Contacter>)data.getSerializableExtra("contacter");
                for(int i=0; i<contacterList.size(); i++){
                    str_cardNo=contacterList.get(i).getCardNo();

                }
                mContacterList = contacterList;
//                mTouristAdapter =new TouristAdapter();
//                mTouristAdapter.setmOnRecyclerViewItemClickListener(this);
//                mRecyclerView.setAdapter(mTouristAdapter);
                mTouristAdapter.notifyDataSetChanged();
            }
        }
        if(requestCode == RESULT_MEMO){
            if(resultCode == RESULT_OK){
                if("".equals(data.getSerializableExtra("memo"))){
                    memo="";
                    mMemoTextView.setText("");
                }else{
                    memo=data.getStringExtra("memo");
                    mMemoTextView.setText(memo);

                }

            }
        }
    }

    private class TouristAdapter extends RecyclerView.Adapter<TouristViewHolder>{
        private SubmitOrderActivity mOnRecyclerViewItemClickListener;
        private SubmitOrderActivity mOnTouristDeleteListener;
        @Override
        public TouristViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(SubmitOrderActivity.this);
            View view = layoutInflater.inflate(R.layout.tourist_recycle_item, parent, false);
            return new TouristViewHolder(view);
        }

        @Override
        public void onBindViewHolder(TouristViewHolder holder, final int position) {
            Contacter contacter=mContacterList.get(position);
            holder.bindData(contacter);
            holder.mEditorImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mOnRecyclerViewItemClickListener.onClickInnerCtrl(position);
                }
            });
            holder.mTouristDeleteImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mOnTouristDeleteListener.onClickDeleteTourist(position);

                }
            });



        }

        @Override
        public int getItemCount() {
            return mContacterList.size();
        }
        public void setmOnRecyclerViewItemClickListener(SubmitOrderActivity mOnRecyclerViewItemClickListener) {
            this.mOnRecyclerViewItemClickListener = mOnRecyclerViewItemClickListener;
        }
        public void setmOnTouristDeleteListener(SubmitOrderActivity mOnTouristDeleteListener){
            this.mOnTouristDeleteListener=mOnTouristDeleteListener;
        }
    }

    private class TouristViewHolder extends RecyclerView.ViewHolder{
        private ImageView mTouristDeleteImageView;
        private TextView mTouristNameTextView;
        private TextView mTelephoneTextView;
        private TextView mTelephoneNumberTextView;
        private TextView mIdCardTextView;
        private TextView mIdCardNumberTextView;
        private ImageView mEditorImageView;
        public TouristViewHolder(View itemView) {
            super(itemView);
            mTouristDeleteImageView=(ImageView) itemView.findViewById(R.id.imageView_tourist_tourist);
            mTouristNameTextView=(TextView)itemView.findViewById(R.id.textView_tourist_name);
            mTelephoneTextView=(TextView)itemView.findViewById(R.id.textView_telephone);
            mTelephoneNumberTextView=(TextView)itemView.findViewById(R.id.textView_telephoneNumber);
            mIdCardTextView=(TextView)itemView.findViewById(R.id.textView_idcard_number);
            mIdCardNumberTextView=(TextView)itemView.findViewById(R.id.textView_incard_number_details);
            mEditorImageView=(ImageView)itemView.findViewById(R.id.imageView_editor);
        }

        public void bindData(Contacter contacter) {
            mTouristNameTextView.setText(contacter.getName());
            mTelephoneNumberTextView.setText(contacter.getTelephone());
            mIdCardNumberTextView.setText(contacter.getCardNo());

        }
    }

}